package com.test45_JUC;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo03_Test {

    public static void main(String[] args) throws Exception {
        // MyBank1.test();
        MyBank2.test();
    }
}

/**
 * 传统方式
 */
class MyBank1 {
    public static int money = 0;    // 模拟银行存款

    public static void test() throws Exception {
        int[] data = new int[] {100, 200, 300};     // 要存款的总额
        for (int x = 0; x < data.length; x++) {     // 存款线程配置
            final int temp = x;
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);   // 100毫秒延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // money += data[temp];
                save(data[temp]);
            }).start();
        }
        TimeUnit.SECONDS.sleep(2);
        System.out.println("【计算完成】最终的存款总额：" + money);
    }

    // 存款方法
    public static synchronized void save(int m) {
        money += m;
    }
}

/**
 * 使用原子操作类
 */
class MyBank2 {
    public static AtomicInteger money = new AtomicInteger();    // 模拟银行存款

    public static void test() throws Exception {
        int[] data = new int[] {100, 200, 300};     // 要存款的总额
        for (int x = 0; x < data.length; x++) {     // 存款线程配置
            final int temp = x;
            new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);   // 100毫秒延迟
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                money.addAndGet(data[temp]);
            }).start();
        }
        TimeUnit.SECONDS.sleep(2);
        System.out.println("【计算完成】最终的存款总额：" + money);
    }
}